package io.qar.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.qar.commons.mybatis.service.impl.CrudServiceImpl;
import io.qar.dto.CfgSrcFtpFileDTO;
import io.qar.dto.FtpParamDTO;
import io.qar.service.FtpService;
import io.qar.dao.CfgSrcFtpFileDao;
import io.qar.entity.CfgSrcFtpFileEntity;
import io.qar.service.CfgSrcFtpFileService;
import io.qar.utils.FtpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 源FTP表
 *
 * @author yyyyjinying
 * @since 3.0 2023-11-03
 */
@Service
public class CfgSrcFtpFileServiceImpl extends CrudServiceImpl<CfgSrcFtpFileDao, CfgSrcFtpFileEntity, CfgSrcFtpFileDTO> implements CfgSrcFtpFileService {

    @Autowired
    private FtpService ftpService;

    @Autowired
    private FtpUtils ftpUtils;

    @Override
    public QueryWrapper<CfgSrcFtpFileEntity> getWrapper(Map<String, Object> params) {
        QueryWrapper<CfgSrcFtpFileEntity> wrapper = new QueryWrapper<>();


        return wrapper;
    }

    /**
     * 全量插入数据
     *
     * @param ftpParamDTO
     * @return
     */
    @Override
    public boolean insertBatchSrcFtpFile(FtpParamDTO ftpParamDTO) {
        QueryWrapper<CfgSrcFtpFileEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("src_username", ftpParamDTO.getUsername());
        List<CfgSrcFtpFileEntity> list = baseDao.selectList(queryWrapper);
        if (list.size() > 0) {
            return false;
        }
        int srcUsernameCount = baseDao.getSrcUsernameCount();
        List<CfgSrcFtpFileEntity> allTreeFileLists = ftpService.getAllTreeFileLists(ftpParamDTO, srcUsernameCount + 1);
        return super.insertBatch(allTreeFileLists);
    }

    @Override
    public boolean updateBatchFromDateTimeFile(FtpParamDTO ftpParamDTO){

        Map<String, Object> newMap = baseDao.getCreateName(ftpParamDTO.getUsername());
        Date fileCreateTime = (Date) newMap.get("file_create_time");
        String pid = (String) newMap.get("pid");
        pid = pid.split("-")[0];
        List<CfgSrcFtpFileEntity> allTreeFileLists = ftpService.getAllTreeFileLists(ftpParamDTO,  Integer.valueOf(pid));
        List<CfgSrcFtpFileEntity> collect = allTreeFileLists.stream().filter(item -> {
            int compare = DateUtil.compare(item.getFileCreateTime(), fileCreateTime);
            if (compare > 0) {
                return true;
            }
            return false;
        }).collect(Collectors.toList());

        System.out.println(collect);

        QueryWrapper<CfgSrcFtpFileEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("src_username", ftpParamDTO.getUsername());
        List<CfgSrcFtpFileEntity> list = baseDao.selectList(queryWrapper);

        List<CfgSrcFtpFileEntity> resList = new ArrayList<>();

        for (int i = 0; i < collect.size(); i++) {
            CfgSrcFtpFileEntity fiteItem = collect.get(i);
            if (fiteItem.getFilePath().length() == 1) {
                continue;
            }
            int subNum = 0;
            for (CfgSrcFtpFileEntity dataItem : list) {

                String separatorPath = ftpUtils.getSeparatorPath(dataItem.getFilePath());
                // name路径不相等，filePath路径相等， pid相等，顺序序获取设置id
                if ((!fiteItem.getName().equals(separatorPath)) && fiteItem.getFilePath().equals(dataItem.getFilePath())) {
                    subNum++;
                    fiteItem.setPid(dataItem.getPid());
                    fiteItem.setId(getSubPid(list, resList, dataItem.getPid(), subNum));
                    resList.add(fiteItem);
                    break;
                }
            }


            int num = 0;
            for (CfgSrcFtpFileEntity resItem : resList) {
                // 如果是同一条数据跳出循环
                if (fiteItem.getName().equals(resItem.getName()) && fiteItem.getFilePath().equals(resItem.getFilePath())) {
                    break;
                }

                String separatorPath = ftpUtils.getSeparatorPath(fiteItem.getFilePath());

                if (resItem.getName().equals(separatorPath)) {
                    num++;
                    fiteItem.setPid(resItem.getId());
                    fiteItem.setId(getSubPid(list, resList, resItem.getId(), num));
                    resList.add(fiteItem);
                    break;
                }

            }
        }

        return super.insertBatch(resList);
    }

    public String getSubPid(List<CfgSrcFtpFileEntity> listData, List<CfgSrcFtpFileEntity> listFile, String pid, int num){
        List<Integer> ids = new ArrayList<>();
        for (CfgSrcFtpFileEntity listDatum : listData) {
            if (listDatum.getPid().equals(pid)) {
                String[] split = listDatum.getId().split("-");
                ids.add(Integer.valueOf(split[split.length - 1]));
            }
        }

        for (CfgSrcFtpFileEntity entity : listFile) {
            if (entity.getPid().equals(pid)) {
                String[] split = entity.getId().split("-");
                ids.add(Integer.valueOf(split[split.length - 1]));
            }
        }

        return pid + "-" +(getMax(ids) + num);
    }

    private int getMax(List<Integer> ids){
        if (ids.size() == 0) {
            return 0;
        }
        int max = ids.get(0);
        for (int i = 1; i < ids.size(); i++) {
            int n = ids.get(i);
            if ( n > max) {
                max = n;
            }
        }
        return max;
    }

}